#include <QRegExp>

#include "Converter.h"

Converter::Converter(const QString &bin, QObject *parent): QProcess(parent),
	_converter(bin)
{
	connect(&_watchOutputTimer, SIGNAL(timeout()), this, SLOT(poll()));
	
	connect(this, SIGNAL(finish(int, QProcess::ExitStatus)), this, SLOT(cleanup(int, QProcess::ExitStatus)));
}

Converter::~Converter()
{
	abort();
}

void Converter::abort()
{
	terminate();
	
	if (waitForFinished(3000) == false)
		kill();
}

void Converter::setArguments(const QString &args)
{
	_args = args;
}

void Converter::convert(const QString &args)
{
	if (args.isNull())
		start(_converter + " " + _args);
	else
		start(_converter + " " + args);
	
	// count elapsed time
	_elapsedTime.start();
	
	// polling process output once per 5 seconds
	_watchOutputTimer.start(5000);
}

bool Converter::isRunning() const
{
	return state() != QProcess::NotRunning;
}

void Converter::poll()
{
	QStringList lines;
	
	// stderr
	_stderr += readAllStandardError();
	_stderr.replace(QRegExp("\x0D\x0A|\x0D|\x0A"), "\n");
	lines = _stderr.split('\n');
	if (1 < lines.count())
	{
		int limit = lines.count() - 1;
		for (int i = 0; i != limit; ++i)
		{
			emit stderrLineOutput(lines[i]);
		}
		
		_stderr = lines[limit];
	}
	
	// stdout
	_stdout += readAllStandardOutput();
	_stdout.replace(QRegExp("\x0D\x0A|\x0D|\x0A"), "\n");
	lines = _stderr.split('\n');
	if (1 < lines.count())
	{
		int limit = lines.count() - 1;
		for (int i = 0; i != limit; ++i)
		{
			emit stdoutLineOutput(lines[i]);
		}
		
		_stdout = lines[limit];
	}
}

int Converter::timeElapsed() const
{
	return _elapsedTime.elapsed();;
}

void Converter::cleanup(int r, QProcess::ExitStatus status)
{
	_watchOutputTimer.stop();
	_stderr.clear();
	_stdout.clear();
}
